package backtrack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 77. 组合
 * User: Li_yizYa
 * Date: 2025/6/12
 * Time: 21:44
 */
public class Solution1 {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ret = new ArrayList<>();
        if (n <= 0 || n < k) {
            return ret;
        }
        List<Integer> tmp = new ArrayList<>();
        backTracking(ret, tmp, 1, n, k);
        return ret;
    }

    /**
     * 未剪枝
     * @param ret
     * @param tmp
     * @param cur
     * @param n
     * @param k
     */
    private void backTracking(List<List<Integer>> ret, List<Integer> tmp, int cur, int n, int k) {
        if (tmp.size() == k) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = cur; i <= n; i++) {
            tmp.add(i);
            backTracking(ret, tmp, i + 1, n, k);
            tmp.remove(tmp.size() - 1);
        }
    }

    /**
     * 剪枝
     * @param ret
     * @param tmp
     * @param cur
     * @param n
     * @param k
     */
    private void backTracking1(List<List<Integer>> ret, List<Integer> tmp, int cur, int n, int k) {
        if (tmp.size() == k) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = cur; i <= n - (k - tmp.size()) + 1; i++) {
            tmp.add(i);
            backTracking1(ret, tmp, i + 1, n, k);
            tmp.remove(tmp.size() - 1);
        }
    }
}
